import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import { getUserInfoAPI } from '@/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '', // 保存token
    userInfo: {}// 保存用户信息
  },
  getters: {
    // username (state) {
    //   return state.userInfo.username
    // }
    username: state => state.userInfo.username, // 用户名字
    nickname: state => state.userInfo.nickname, // 用户昵称
    user_pic: state => state.userInfo.user_pic// 用户头像
  },
  mutations: {
    // 保存token到vuex
    updateToken (state, val) {
      state.token = val
    },
    // 保存用户信息到state
    updateUserInfo (state, info) {
      state.userInfo = info
    }
  },
  actions: {
    // 使用token获取用户信息
    async initUserInfo (store) {
      const res = await getUserInfoAPI()
      if (res.data.code === 0) {
        store.commit('updateUserInfo', res.data.data)
        // console.log(res.data.data)
      }
    }
  },
  modules: {
  },
  plugins: [
    createPersistedState()
  ]
})
